package ink.yql.service.Impl;

import ink.yql.dao.DynamicDao;
import ink.yql.dao.LeaveaMessageDao;
import ink.yql.dao.PointDao;
import ink.yql.dao.UserDao;
import ink.yql.model.Dynamic;
import ink.yql.model.User;
import ink.yql.service.DynamicService;
import ink.yql.util.RestObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import yql.myutil.MyDate;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Service
@Transactional
public class DynamicServiceImpl implements DynamicService {
    @Autowired
    private DynamicDao dynamicDao;
    @Autowired
    private PointDao pointDao;
    @Autowired
    private LeaveaMessageDao leaveaMessageDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private HttpServletRequest req;

    @Override
    public RestObject getByUid() {
        // 获取session中的用户
        User user = (User) req.getSession().getAttribute("user");
        if (user == null) {
            return RestObject.builder().code("404").message("请先登录").build();
        }
        return getByUid(user.getUid());
    }

    @Override
    public RestObject getByUid(Integer uid) {
        List<Dynamic> list = dynamicDao.getByUid(uid);
        return RestObject.builder().code("200").message("查询自己的动态成功").data(list).build();
    }

    @Override
    public RestObject addOneDynamic(Dynamic dynamic) {
        try {
            User user = (User) req.getSession().getAttribute("user");
            if (user == null) {
                return RestObject.builder().code("404").message("请先登录").build();
            }
            dynamic.setDaddtime(new MyDate().toString());
            dynamic.setUid(user.getUid());
            dynamicDao.addOne(dynamic);
            return RestObject.builder().code("200").message("发布动态成功").build();
        } catch (Exception e) {
            return RestObject.builder().code("404").message("发布动态失败").data(e.getMessage()).build();
        }
    }

    @Override
    public RestObject deleteByDid(Integer did) {
        // did是目标id   1 是动态  0是点赞
        // 删除点赞
        Integer praise = pointDao.deleteByLuidAndPststusAndPtype(did, 1, 0);
        // 删除点嘘
        Integer hiss = pointDao.deleteByLuidAndPststusAndPtype(did, 1, 0);
        // 删除评论
        leaveaMessageDao.deleteByOtheridAndLtype(did, 1);
        // 删除动态
        dynamicDao.deleteDid(did);
        return RestObject.builder().code("200").message("删除动态成功").build();
    }
}
